import dayjs from "dayjs"
import isBetween from "dayjs/plugin/isBetween"
import { create } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"

import type {
  ChatMessageAction,
  ChatMessageBaseType,
  ChatMessageState,
  ChatMessageType
} from "~type/chatType"
import { getCurrentTimestamp } from "~util"
import { StoreageKEY } from "~util/const"
import { storage } from "~util/sotrage"

dayjs.extend(isBetween)
export const useChatStore = create<ChatMessageState & ChatMessageAction>()(
  persist(
    (set, get) => ({
      contents: [],
      createTime: "",
      chat: {},
      setChat: (chat?: ChatMessageBaseType) => {
        const chatState = { ...chat, createTime: getCurrentTimestamp() }
        // chatState.createTime = getCurrentTimestamp()
        set({ chat: chat! && chat.content ? chatState : {} })
      },
      setContents: function (contents: ChatMessageType[]) {
        const addTimeContent = contents.map((item) => {
          if (!item.createTime) {
            item.createTime = getCurrentTimestamp()
          }
          return item
        })
        // console.log("addTimeContent", addTimeContent)
        set({
          contents: [...addTimeContent],
          createTime: getCurrentTimestamp()
        })
      },
      getContents({ start, end, timestamp }) {
        const contents = [...get().contents]
        // console.log(contents)
        if (end > contents.length) {
          throw new Error("end must be greater than")
        }
        const conlist = contents.slice(
          start ? start : 0,
          end ? end : contents.length
        )

        const resultData = conlist.filter((item) => {
          const beforeTime = getCurrentTimestamp(timestamp ? timestamp : "")

          const afterTime = getCurrentTimestamp()
          const isTime = dayjs(item.createTime).isBetween(beforeTime, afterTime)
          if (isTime) {
            return item
          } else {
            return
          }
        })
        // console.log(resultData)
        return resultData
      },
      addContent: function (content: ChatMessageType) {
        set((state) => ({
          contents: [...state.contents, content],
          createTime: dayjs().toString()
        }))
      },
      delContent: () => {
        set({ contents: [], chat: {} })
      }
    }),
    {
      name: StoreageKEY.chat,
      storage: createJSONStorage(() => storage)
    }
  )
)
